﻿using UnityEngine;


/// <summary>
/// 斜俯视角游戏专用摇杆。有MinLimit和MaxLimit
/// </summary>
public class WorldJoystick : MonoBehaviour
{
    public GameObject Circle;
    public GameObject Knob;
    protected RectTransform BaseTransform;
    protected RectTransform CircleTransform;
    protected RectTransform KnobTransform;

    public float ValidDisplacementMinLimit = 20;

    protected Vector2 Displacement;

    void Start()
    {
        BaseTransform = GetComponent<RectTransform>();
        if (Circle != null)
        {
            CircleTransform = Circle.GetComponent<RectTransform>();
        }
        if (Knob != null)
        {
            KnobTransform = Knob.GetComponent<RectTransform>();
        }
    }

    /// <summary>
    /// 是否超过下限，和State不同的是，在InputUp之后仍然记录着本次拖拽的最新或最后一刻的状态，不能用State直接判断
    /// </summary>
    public bool IsValidDrag;


    #region MyRegion

    protected virtual void OnInputDown(Vector2 pressPos, Vector2 currentPos)
    {
        Displacement = Vector2.zero;
    }

    protected virtual void OnInputDrag(Vector2 pressPos, Vector2 currentPos)
    {
        CalcDisplacements(pressPos, currentPos);
    }

    protected virtual void OnInputUp(Vector2 pressPos, Vector2 currentPos)
    {
        IsValidDrag = false;
    }

    public virtual void ClearState()
    {
        IsValidDrag = false;

        if (KnobTransform) KnobTransform.anchoredPosition3D = new Vector3(0, 0, 0);
    }

    #endregion


    protected void CalcDisplacements(Vector2 pressPosition, Vector2 currentPosition)
    {
        //ScreenDragDisplacement
        Displacement = currentPosition - pressPosition; //屏幕坐标

        IsValidDrag = Displacement.magnitude > ValidDisplacementMinLimit;
    }
}